package com.itheima.controller;

import com.itheima.entity.Result;
import com.itheima.utils.AliyunOSSUtils;
// import lombok.Value;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;


@RestController
public class UploadController {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(DeptController.class);
//    private static final String enpoint = "https://oss-cn-beijing.aliyuncs.com";
//    private static final String bucketName = "java-hm147-tlias";
    @Value("${aliyun.oss.endpoint}")
    private String enpoint;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    /**
     * 文件上传-存储在本地
     * @param username
     * @param age
     * @param file
     * @return
     */
//    @PostMapping("/upload")
//    public Result upload(String username, Integer age, MultipartFile file){
//        log.info("参数：{},{},{}", username, age, file.getOriginalFilename());
//        String uploadDir = "C:\\uploads\\";
//        // 1.获取原始文件名
//        String FileName = file.getOriginalFilename();
//        // 获取扩展名
//        String ext = FileName.substring(FileName.lastIndexOf("."));
//        // 生成随机文件
//        String newFileName = UUID.randomUUID() + ext;
//
//        try {
//            //1.将前端上传文件存到本地
//            // 浏览器路径 localhost:63342/upload.html
//            file.transferTo(new File(uploadDir + newFileName));
//        } catch (Exception e) {
//            System.out.println("文件保持失败！");
//            e.printStackTrace();
//        }
//
//        return Result.success(newFileName);
//    }

    /**
     * 文件上传-存储在本地
     * @param username
     * @param age
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception{
        // 1.获取原始文件名，获取后缀
        String originalFilename = file.getOriginalFilename();
        log.info("参数：{}", originalFilename);
        String extname = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 2.调用阿里云OSS工具类，将文件上传到OSS
        String url = AliyunOSSUtils.upload(enpoint, bucketName, file.getBytes(), extname);

        return Result.success(url);
    }
}
